package com.starblink.wishlist.wishboards.ui.part

import android.app.Activity
import android.graphics.Color
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.basic.style.databinding.BaseLayoutEmptyWishTemplateBinding
import com.starblink.basic.style.view.round.CornerType
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.databinding.CellSimpleProductCardBinding
import com.starblink.wishlist.databinding.FragmentWishBoardsBinding
import com.starblink.wishlist.databinding.ItemBoardChildBinding
import com.starblink.wishlist.databinding.LayoutBoardCreateBinding
import com.starblink.wishlist.databinding.LayoutRelatedTitleBinding
import com.starblink.wishlist.wishboards.ui.WishBoardsVM
import com.starblink.wishlist.wishboards.ui.bean.RvBoardItemEntry
import com.starblink.wishlist.wishboards.ui.cells.*

/**
 * 处理feeds流的事件 风向标 商品合集 运营推荐 及feeds的骨架/空界面
 */
class WishBoardsPart(
    private val mActivity: Activity, var viewBinding: FragmentWishBoardsBinding,
    var viewModel: WishBoardsVM
) {
    var layoutManager: StaggeredGridLayoutManager? = null
    private var mutiItemNumSuffix =
        CommUtils.getString(com.starblink.basic.style.R.string.boards_selected)
    private val feedsAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mBoardsObserver.value!!).apply {
            //类目
            addVhDelegate {
                EmptyBoardsCell(
                    mActivity,
                    BaseLayoutEmptyWishTemplateBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                AddBoardsCell(
                    mActivity,
                    LayoutBoardCreateBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                BoardItemsCell(
                    mActivity,
                    ItemBoardChildBinding.inflate(it.inflater, it, false),
                    choiceClickCallback = { position, isChoice ->
                        //左侧选择点击
                        var entry =
                            viewModel.mBoardsObserver.value!![position] as RvBoardItemEntry
                        entry.hasChoice = isChoice
                        notifyItemChanged(position)
                        //如果有一个没选 全选置为false
                        if (!isChoice) {
                            viewModel.selectAll = false
                        } else {
                            var allSelect = true
                            for (item in viewModel.mBoardsObserver.value!!) {
                                if (item is RvBoardItemEntry) {
                                    allSelect = allSelect && item.hasChoice
                                    if (!allSelect) {
                                        break
                                    }
                                }
                            }
                            viewModel.selectAll = allSelect
                        }
                        //取消或选中一个item
                        switchAllChoiceImg(false, 2)
                    },
                    deleteClickCallback = { model, removePosition ->
                        viewModel.deleteCollItem(model, removePosition) {
                            //取消收藏
                            viewModel.mBoardsObserver.value!!.removeAt(removePosition)
                            viewModel.mBoardsObserver.postValue(viewModel.mBoardsObserver.value)
//                            notifyItemRemoved(removePosition)
//                            notifyItemRangeChanged(
//                                removePosition,
//                                viewModel.mBoardsObserver.value!!.size - removePosition
//                            )
//                            //TODO  删除到0的时候怎么办
//                            //取消收藏 相当于取消一个item
//                            switchAllChoiceImg(false, 2)
                        }
                    }
                )
            }
            addVhDelegate {
                BoardRelatedTitleCell(
                    LayoutRelatedTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                WishProductCell(
                    refreshLayout = viewBinding.page,
                    recyclerView = viewBinding.rv,
                    binding = CellSimpleProductCardBinding.inflate(it.inflater, it, false),
                    spmPageValue = SpmPageDef.Page_10171,
                    cardClick = { model, position ->
                    }
                )
            }

        }
    }

    fun handleVM() {
        layoutManager =
            viewBinding.rv.bindProductFeeds(
                feedsAdapter, horGap = 11,
                verGap = 10
            ) as StaggeredGridLayoutManager?
        viewBinding.rv.itemAnimator = FadeInAnimator()
        viewBinding.rv.isNestedScrollingEnabled = true

        //点击all select
        viewBinding.mutiAllChoiceLay.click {
            //点击全选或反选
            switchAllChoiceImg(selectAllOrReverse = true, 2)
        }

        viewBinding.mutiAllChoiceDel.click {
            //删除弹窗二次确认
            if (viewModel.choiceNum > 0) {
                ConfirmDialog.Builder(mActivity)
                    .setMessage(
                        "Are you sure you want to\n" +
                                "delete ${if (viewModel.choiceNum == 1) "this Board" else "these Boards"}?"
                    )
                    .setCancelButton(com.starblink.basic.style.R.string.cancel) { dialog, _ ->
                        dialog.dismiss()
                    }
                    .setSureButton(com.starblink.basic.style.R.string.delete) { dialog, _ ->
                        dialog.dismiss()
                        viewModel.deleteCollItems()
                    }
                    .setCanCancel(true)
                    .create().show()
            } else {
                toastWishlist("Please select at least 1 item")
            }

        }

    }


    fun dataChange(it: ArrayList<Any>) {
        //添加删除状态太多 没法太精确的同步

//        if (viewModel.pageIndex == 1) {
        feedsAdapter.notifyDataSetChanged()
//        } else {
//            feedsAdapter.notifyItemRangeChanged(
//                viewModel.lastFeedsSize - 1,
//                it.size
//            )
//        }
        viewModel.lastFeedsSize = it.size

        //数据改变了 刷新一次状态
        switchAllChoiceImg(false, 2)
    }

    fun mutiChange(sMode: Boolean) {
        viewModel.choiceMode = sMode

        if (sMode) {
            viewModel.clearChoiceHistory()
            //刷底部显示
            switchAllChoiceImg(false, 2)
            //底部多选出现
            viewBinding.llMutiBtmLay.visible()
        } else {
            viewBinding.llMutiBtmLay.gone()
        }

        changeRvDataAll(selectAllOrReverse = false)
    }

    private fun changeRvDataAll(selectAllOrReverse: Boolean) {
        if (viewModel.mBoardsObserver.value!!.isNotEmpty()) {
            viewModel.mBoardsObserver.value!!.forEach {
                if (it is RvBoardItemEntry) {
                    it.showCheckMode = viewModel.choiceMode
                    if (selectAllOrReverse) {
                        it.hasChoice = viewModel.selectAll
                    } else {
                        it.hasChoice = false
                    }
                }
            }
            feedsAdapter.notifyDataSetChanged()
        }
    }


    /**
     * 所有底部的变化都在这个方法里写
     * @param totalNumTxtType   1 全选模式 | 2 遍历
     * @param change 是否刷新所有items
     */
    private fun switchAllChoiceImg(selectAllOrReverse: Boolean, totalNumTxtType: Int) {
        if (selectAllOrReverse) {
            viewModel.selectAll = !viewModel.selectAll
            changeRvDataAll(selectAllOrReverse = true)
        }

//        YYLogUtils.e("--------------viewModel.selectAll${viewModel.selectAll}------------------")
        if (viewModel.selectAll) {
            viewBinding.mutiAllChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_true))
        } else {
            viewBinding.mutiAllChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_false))
        }

        when (totalNumTxtType) {
            //1 不适应普遍的情况 限制条件多 不利于扩展
//            1 -> {
//                val num = viewModel.getChoiceNum(viewModel.selectAll)
//                viewBinding.mutiChoiceTotalNum.text =
//                    "${num} $mutiItemNumSuffix"
//            }
            2 -> {
                val num = viewModel.refreshChoiceNum()
                viewBinding.mutiChoiceTotalNum.buildSpannableString {
                    if (num == 0) {
                        addText("0") {
                            setColor(Color.parseColor("#64748B"))
                        }
                    } else {
                        addText("$num") {
                            setColor(Color.parseColor("#E11D48"))
                        }
                    }
                    addText(" $mutiItemNumSuffix") {
                        setColor(Color.parseColor("#64748B"))
                    }
                }
            }
        }
        //处理底部两个按钮

        if (viewModel.choiceNum > 0) {
            viewBinding.mutiAllChoiceDel.setCornerRadius(
                CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600).toFloat(),
                CornerType.R_BORDER_COLOR
            )
            viewBinding.mutiAllChoiceDelTxt.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600))
        } else {
            viewBinding.mutiAllChoiceDel.setCornerRadius(
                CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600_opacity50).toFloat(),
                CornerType.R_BORDER_COLOR
            )
            viewBinding.mutiAllChoiceDelTxt.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600_opacity50))
        }
    }

}